<template>
  <div :id="`player-${playerId}`" class="player-component"></div>
</template>

<script setup>
import { onMounted, onDeactivated, onActivated, ref, watch, nextTick } from 'vue'
import { createRandomString } from '@/utils/util.js'
import Player from 'xgplayer';
import HlsPlugin from 'xgplayer-hls'
import 'xgplayer/dist/index.min.css';
import { Events } from 'xgplayer'

const props = defineProps({
  // 传入的视频地址
  url: {
    type: String,
    default: ''
  },
  // 激活的视频索引，用于只播放激活的视频，暂停未激活的视频
  active: {
    type: Boolean,
    default: false
  },
  // 控制栏距离底部高度
  controlsBottom: {
    type: String,
    default: '0'
  },
  // 播放模式，可选mp4和hls，默认mp4
  model: {
    type: String,
    default: 'mp4'
  }
})

// 抛出ready、play事件回调
const emits = defineEmits(['ready', 'play'])

// 播放器实例
const player = ref()

// 播放器id，随机生成
const playerId = ref(createRandomString())

function init() {
  // 将props中参数结构
  const { url, active, model } = props

  if (model == 'hls') {
    player.value = new Player({
      id: `player-${playerId.value}`,
      url: url,
      autoplay: false, // 自动播放，注：浏览器不允许直接自动播放，需要用户交互后才可播放，但是允许在静音状态下自动播放
      loop: true, // 循环播放
      height: '100%',
      width: '100%',
      plugins: [HlsPlugin] // hls插件导入
    })
  } else {
    player.value = new Player({
      id: `player-${playerId.value}`,
      url: url,
      autoplay: false,
      loop: true,
      height: '100%',
      width: '100%',
    })
  }

  // 初始化时，抛出ready回调
  emits('ready', player.value)

  if (active) {
    // 自动播放已激活的视频
    setTimeout(() => {
      startPlay()
    }, 500)
  }

  // 监听播放时，抛出play回调
  player.value?.on(Events.PLAY, () => {
    emits('play')
  })
}

// 开始播放
function startPlay() {
  if (player.value) {
    console.log('视频播放');
    player.value?.play()
  }
}

// 暂停播放
function pausePlay() {
  if (player.value) {
    console.log('视频暂停');
    player.value?.pause()
  }
}

// 销毁播放实例
function destroyPlay() {
  if (player.value) {
    console.log('视频销毁');
    player.value?.destroy()
    player.value = null
  }
}

// 监听视频激活时，播放激活的视频，自动停止未激活的视频，防止多视频叠加播放状态
watch(() => props.active, (newVal) => {
  if (newVal) {
    startPlay()
  } else {
    pausePlay()
  }
})

onMounted(() => {
  nextTick(() => {
    init()
  })
})

// keep-alive的生命周期，激活
onActivated(() => {
  if (props.active) {
    startPlay()
  }
})

// keep-alive的生命周期，失活
onDeactivated(() => {
  console.log('视频失活--->', `player-${playerId.value}`);
  pausePlay()
})

// 暴露出某些方法，父组件可使用ref拿到dom实例后点其中的方法
defineExpose({
  startPlay,
  pausePlay,
  destroyPlay
})
</script>

<style lang="scss" scoped>
// 绑定controlsBottom属性，动态渲染控制栏距离底部高度
$controls-bottom: v-bind('controlsBottom');

.player-component {
  :deep(.xgplayer-controls) {
    bottom: $controls-bottom;
  }
}
</style>